# -*- coding: utf-8 -*-
#from __future__ import unicode_literals

from django.shortcuts import render

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from live_api import pili
from live_api.tools.Output_Helper import *
from live_api.tools.constant import *
from live_api.tools.roomAPI import *
import live_api.tools.utils_file as ufile
import os
import random
import time
import sys

reload(sys)
sys.setdefaultencoding("utf-8")


def env(key):
    if key in os.environ:
        return os.environ[key]
    else:
        return ""


# Create your views here.
# 创建直播间
@csrf_exempt
def room_start(request):
    db =DB.getDB()
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("name", "actorid", "live_picurl", "cdes", "ctype", "privateflag",
                            "roompay", "roompwd", "payforchat", "privatechat", "location","orientation")
        info.start_date = info.tick()
        info.par1 = 1
        info.par2 = 0
        if info.live_picurl=='':
            info.live_picurl=datais.header
        else:
            info.live_picurl=info.live_picurl[len(datais.url_img):]
        info=api_createRoom(info)
        # 创建直播间   accid,name='',announcement='',broadcasturl='',ext=''
        sql = sqlr("select * from user where id=$actorid", info)
        n, rows = db.query(sql)
        info.accid=rows[0]['accid']
        netease_info = p.createRoom(info.accid, info.name,broadcasturl=info.rtmp_play_url)
        netease_info=json.loads(netease_info)
        info.room_num = netease_info['chatroom']['roomid']
        # 在video表中插入room信息和video信息
        maxid_video = maxid("video", "id")
        info.id = maxid_video
        # print "info.id:",info.id
        location=info.location.split('-')
        if len(location)>0:
            info.l_province=location[0]
        if len(location)>1:
            info.l_city=location[1]
        if len(location)>2:
            info.l_area=location[2]
        # info.id_area=select_location(location)
        sql = sqlr(
                "insert into video(id,id_actor,room_num,cname,broadcasturl,publishurl,publishurl_m3u8,live_picurl,cdes,ctype,privateflag,"
                "roompwd,roompay,payforchat,privatechat,location,start_date,l_province,l_city,l_area,orientation,par1,par2) values($id,$actorid,$room_num,$name,$rtmp_play_url,"
                "$rtmp_publish_url,$hls_play_url,$live_picurl,$cdes,$ctype,$privateflag,$roompwd,$roompay,$payforchat,$privatechat,$location,$start_date,$l_province,$l_city,$l_area,$orientation,$par1,$par2)",
                info)
        db.execute(sql)
        ret.msg = "直播间创建成功!"
        # 创建者信息
        ret.actor_info = get_user_info(info.actorid)
        # 视频信息
        sql = sqlr("select * from video where id=$id", info)
        n, rows = db.query(sql)
        ret.video_info = out_farmat_video(rows,0)
    except Exception, e:
        ret.code = 1011
        ret.msg = str(e)
        # ret.msg = '7牛云异常'
        # print(str(e))
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


@csrf_exempt
def Push_back(request):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)#
        info.checkPostEmpty('title')
        # sql = "update user_count set n_praise=%s where id_user=%s" % (info.nlike, rows[0]['id_actor'])
        sql = "update video set par1=0 where broadcasturl like '%s%s' and ctype=0" % ("%", info.title)
        db.execute(sql)
        ret.code = 200
        ret.msg = 'ok'
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())
@csrf_exempt
def live_set(request):
    ret = ReturnJ()
    try:
        info = INFO(request)  #
        info.checkPostEmpty('actor_id')
        sql = "select control_comment,control_gif,control_actor from actor where id=%s" % info.actor_id
        db = DB.getDB()
        n, room = db.query(sql)
        ret.set = room[0]
        ret.code = 200
        ret.msg = 'ok'
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())






@csrf_exempt
def CloseRoom(request):
    ret = ReturnJ()
    try:
        info = INFO(request)  #
        info.checkPostEmpty('id_actor')
        sql = "select room_num from video where id_actor=%s and par2=0" % (info.id_actor)
        db = DB.getDB()
        n, room = db.query(sql)
        for i in room:
            info.room_num = i['room_num']
            print info.room_num
            sql = "select * from video where room_num=%s and par2=0" % (info.room_num)
            print sql
            db = DB.getDB()
            n, rows = db.query(sql)
            # sql = "update user_count set n_praise=%s where id_user=%s" % (info.nlike, rows[0]['id_actor'])
            sql = "select * from user where id=%s" % rows[0]['id_actor']
            n, user = db.query(sql)
            p.closeRoom(rows[0]['room_num'], user[0]['accid'])
            print i['room_num'] ,'ok'
        ret.code = 200
        ret.msg = 'ok'
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())



# Create your views here.
# 查询直播间
@csrf_exempt
def room_query(request):
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty('room_num')
        # 查询直播间
        netease_info = p.queryRoom(int(info.room_num))
        netease_info=json.loads(netease_info)
        ret.chatroom = netease_info['chatroom']
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))
    return HttpResponse(ret.toJson())


# 关闭直播间
@csrf_exempt
def room_end(request, id):
    ret = ReturnJ()
    db =DB.getDB()
    try:
        info = INFO(request)
        info.id = id

        sql = "select ctype from video where id=%s" % id
        db = DB.getDB()
        n, room = db.query(sql)
        if int(room[0]['ctype']) == 1:
            ret.msg = "直播间已经关闭!"
            ret.code = 1011
        else:
            info.end_date = info.tick()
            info.closeroom = 0#主动关闭房间
            room_backwrite(request,info)
            ret.msg = "成功关闭直播间!"
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


# 直播间断播回调
@csrf_exempt
def room_callback(request):
    ret = ReturnJ()
    db =DB.getDB()
    try:
        info = INFO(request)#
        info.checkPostEmpty('title')
        info.closeroom = 1#回调关闭房间
        info.key=info.title
        # print 00000000000000000000,info.closeroom,info.key
    # print('0000000000000000')
        room_backwrite(request,info)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())

def room_backwrite(request,info):
    if info.closeroom==0:#主动关闭房间
        sql = sqlk("select * from video where id =$id and ctype=0", id=info.id)
        db =DB.getDB()
        n,rows = db.query(sql)
        if n==0:
            raise Exception('未找到这个(%s)房间' % info.id)
        broadcasturl=rows[0]['broadcasturl']
        test_url='rtmp://pili-live-rtmp.xiancity.cn/liuhualive/'
        info.key=broadcasturl[len(test_url):]
        info.title=broadcasturl[len(test_url):]
        info.end_date=rds.get("room_id_beatheart_end_date_%s"% rows[0]['room_num'])
    elif  info.closeroom==1:#回调关闭房间
        sql = "select * from video where broadcasturl like '%s%s' and ctype=0"%("%",info.key)
        db =DB.getDB()
        n,rows = db.query(sql)
        if n==0:
           return
        info.end_date=rds.get("room_id_beatheart_end_date_%s"% rows[0]['room_num'])
    else:
        return
    info.city=''
    p.sendRoomMsg(rows[0]['room_num'],info.tick(),'new_liuhua_%s'%rows[0]['id_actor'],0,**{"customType":5})
    sql = "select * from user where id=%s" % rows[0]['id_actor']
    n, user = db.query(sql)
    p.closeRoom(rows[0]['room_num'], user[0]['accid'])
    ret_data=api_saveas(info)
    if 'fname' in ret_data:
        info.city=ret_data['fname']
    info=room_counter(info, rows[0]['room_num'])
    info.ctype=1
    sql = "select nlooked from video where broadcasturl like '%s%s'" % ("%",info.title)
    n, row = db.query(sql)
    if int(row[0]['nlooked']) == 0:
        sql = "update video set nlooked=%s,ncustomer=%s,end_date=%s,duration=100,ctype=%s, city='%s' where broadcasturl like '%s%s'"%(info.nlooked,info.ncustomer,info.tick(),info.ctype,info.city,"%",info.title)
    # sql = "update video set nlooked=%s,ncustomer=%s,end_date=%s,duration=100,ctype=%s, city='%s' where broadcasturl like '%s%s'"%(info.nlooked,info.ncustomer,info.tick(),info.ctype,info.city,"%",info.title)
    # print("sql:")
    # print(sql)
        db.execute(sql)
    room_counter_expire(rows[0]['room_num'])
    return



# 直播间统计信息
@csrf_exempt
def room_counter(info, id):
    info.ncustomer=rds.count("room_id_online_user_%s"%id)
    info.nlooked=rds.count("room_id_users_%s"%id)
    # info.nlike=rds.count("room_id_like_%s"%id)
    return info


# 过期直播间统计信息
@csrf_exempt
def room_counter_expire(id):
    rds.delete("room_id_online_user_%s"%id)
    rds.delete("room_id_users_%s"%id)
    rds.delete("room_id_beatheart_end_date_%s"%id)
    # rds.delete("room_id_like_%s"%id)


# 直播间心跳
@csrf_exempt
def room_beatheart(request, id):
    ret = ReturnJ()

    try:
        info = INFO(request)
        info.id = id
        info.end_date = info.tick()
        ret.room_flag=False
        end_date=rds.get("room_id_beatheart_end_date_%s"%id )

        if end_date==None:
            sql = sqlk("select * from video where  room_num=$id and ctype=0", id=info.id)
            db = DB.getDB()
            n,rows = db.query(sql)
            if n>0:
                rds.set("room_id_beatheart_end_date_%s"%id, info.end_date)  # 心跳
                ret.msg = "直播间正在直播中!"
                ret.room_flag=True
                addrobot(request,id)
        else:
            rds.set("room_id_beatheart_end_date_%s"%id, info.end_date)  # 心跳
            ret.msg = "直播间正在直播中!"
            ret.room_flag=True
            addrobot(request, id)


    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res

l = []
def addrobot(request,room_num):
    db = DB.getDB()
    s = sqlk("select * from video where  room_num=$id and ctype=0", id=room_num)
    m, rows = db.query(s)
    if m > 0:

        # rand1 = random.randint(105,214)
        # rand2 = random.randint(105,214)
        # # 46  364
        # # print rand1,rand2
        #
        # if rand1 > rand2:
        #     rand1,rand2 = rand2,rand1
        for i in range(46, 364):
            l.append(i)
        n = random.sample(l,40)
        for i in n:
            # accid = 'liuhua_'+str(i)
            accid = 'new_liuhua_'+str(i)
            p.addRobot(room_num, *[accid,])
            rds.add("room_id_online_user_%s"%room_num,str(i))  # 在线用户列表
            rds.add("room_id_users_%s"%room_num, str(i))  # 进入过房间的用户
        ncustomer = rds.count("room_id_online_user_%s"%room_num) 
        ncustomer = int(ncustomer) * 3
        # nlike = rds.count("room_id_like_%s" % room_num)
        # print count
        sql = "update video set ncustomer=%s where room_num=%s"%(ncustomer,room_num)
        db.execute(sql)


# 用户进出直播间
@csrf_exempt
def room_in_out(request, id):
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty('id_user', 'ctype')
        # 进入
        # print info.ctype
        if info.ctype == "0":

            sql = sqlk("select * from video where  room_num=$id and ctype=0", id=id)
            db = DB.getDB()
            n, rows = db.query(sql)
            ret.room_flag = True
            if n > 0:
                # print 'key:' + 'room_id_online_user_' + id, ' value:' + info.id_user
                rds.add("room_id_online_user_%s"%id, info.id_user)  # 在线用户列表
                rds.add("room_id_users_%s"%id, info.id_user)  # 进入过房间的用户
                # print "个数:", rds.count("room_id_online_user_" + id)
                ret.msg = "进入成功"
            else:
                ret.room_flag = False
                ret.msg = "房间已关闭"

        else:  # 退出

            # print 'key:'+'room_id_online_user_' + id,' value:'+info.id_user
            rds.sremove('room_id_online_user_' + id, info.id_user)

            # rds.delete('room_id_online_user_' + id, info.id_user)
            # print "个数:", rds.count("room_id_online_user_" + id)
            ret.msg = "退出成功"

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())


# 房间用户列表
@csrf_exempt
def room_users(request, id):
    ret = ReturnJ()
    db =DB.getDB()
    try:
        room_online_users = rds.members("room_id_online_user_" + id)
        online_users = ''
        for online_user in room_online_users:
            online_users = online_users + online_user + ','

        online_users = online_users[:-1]
        rows = []
        if online_users != '':
            sql = sqlk("select * from user where id in (#online_users) limit 50", online_users=online_users)
            n, rows = db.query(sql)
        ret.user_info = out_farmat_users(rows)
        ret.msg = "成功"
        sql1 = sqlk("select ncustomer,nlike from video WHERE room_num=#id", id=id)
        n, rows = db.query(sql1)
        ret.likeNumber = rows[0]['nlike']
        ret.ncustomer = rows[0]['ncustomer']

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


# 获取直播间信息
@csrf_exempt
def room_info(request, id):
    ret = ReturnJ()
    db =DB.getDB()
    info = INFO(request)
    try:
        # 房间基本信息
        sql = sqlk("select * from video where room_num =$id", id=id)
        n, rows_room = db.query(sql)
        # print rows_room
        rows_room[0]['nlooked'] = rows_room[0]['nlooked'] * 9
        ret.room_info = rows_room
        id_actor = rows_room[0]['id_actor']
        # print "id_actor:", id_actor

        # 创建者信息
        ret.room_actor =get_user_info(id_actor)
        # 统计信息在线人数等
        # x = room_counter(info, id)
        # print x
        sql = sqlk("select nlike,nlooked,ncustomer from video where room_num=$id", id=id)
        n, rows_counter = db.query(sql)
        rows_counter[0]['nlooked'] = rows_counter[0]['nlooked'] * 9
        ret.room_counter = rows_counter

        ret.msg = "成功"

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res
